
<template>
  <div class="roleList">
    <div class="topBtn">
      <el-button
        size="mini"
        @click="addRoleClick"
        type="success"
        plain
        icon="el-icon-plus"
        v-has="'system:role:add'"
        >新增角色</el-button
      >
    </div>

    <div class="tableBox" ref="tableBoxRef">
      <el-table
        ref="multipleTable"
        v-loading="tableLoading"
        row-key="id"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        :height="screenHeight - 200"
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          align="center"
          label="角色名称"
           
        >
        </el-table-column>
        <el-table-column
          align="center"
           
          label="角色编码"
        >
          <template slot-scope="scope"> {{ scope.row.code }} </template>
        </el-table-column>
        <el-table-column align="center" label="状态" >
          <template slot-scope="scope">
            <el-switch
              :disabled="permissions.indexOf('system:role:status') == -1"
              @change="statusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" >
          <template slot-scope="scope">{{
            scope.row.createTime | formatDate
          }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              @click="editClick(scope.row)"
              v-has="'system:role:edit'"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
      :title="title"
      :visible.sync="addEditDialogVisible"
      width="580px"
      top="5vh"
      @open="addEditDialogOpen"
      class="addEditRoleDialog"
    >
      <div class="content">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditFormRef"
        >
          <el-form-item prop="roleNameInput" label="角色名称：">
            <div class="item">
              <el-input
                size="mini"
                v-model="addEditForm.roleNameInput"
                placeholder="请输入角色名称"
                maxlength="32"
              >
              </el-input>
            </div>
          </el-form-item>

          <el-form-item
            prop="roleCodeInput"
            class="roleCode"
            label="角色编码："
          >
            <div class="item">
              <el-input
                size="mini"
                v-model="addEditForm.roleCodeInput"
                placeholder="请输入角色编码"
                maxlength="32"
              >
                <template slot="prepend">ROLE_</template>
              </el-input>
            </div>
          </el-form-item>

          <el-form-item label="权限列表：" prop="checkedIds">
            <div class="item permissions">
              <el-tree
                ref="treeRef"
                :data="data"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                :check-strictly="isCheck"
                :default-expanded-keys="addEditForm.checkedIds"
                :default-checked-keys="addEditForm.checkedIds"
              >
              </el-tree>
            </div>
          </el-form-item>

          <el-form-item class="btns">
            <el-button size="mini" @click="addEditDialogVisible = false"
              >取 消</el-button
            >
            <el-button
              v-clickForbidden
              size="mini"
              type="primary"
              @click="addEditSaveClick"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      screenHeight: document.documentElement.clientHeight,
      role_: false,
      tableLoading: false,
      tableData: [],
      addEditDialogVisible: false,
      addEditForm: {
        roleNameInput: "",
        roleCodeInput: "",
        checkedIds: [],
      },
      addEditRules: {
        roleNameInput: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleCodeInput: [
          { required: true, message: "角色编码不能为空", trigger: "blur" },
        ],
      },
      title: "新增角色",
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      isCheck: false,
      activeTableCheckedIds: [],
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
  },

  created() {
    this.getPermissionsTreeData();
    this.getRoleList();
  },
  methods: {
    /**
     * 状态更新回调
     * @param {*} row
     */
    async statusChange(row) {
      let data = {
        id: row.id,
        status: row.status,
      };
      this.$api.roleStatus(data).then((response) => {
        if (response.data.code == "00000") {
            this.$message.success("状态更新成功");
          }
      });
    },
    async getPermissionsTreeData() {
      this.$api.menuList().then((response) => {
        this.data = response.data.result;
      });
    },

    /**
     * 获取角色列表
     * @param {*}
     */
    async getRoleList() {
      this.tableLoading = true;
      this.$api.roleList().then((response) => {
        this.tableData = response.data.result;
        this.tableLoading = false;
      });
    },

    /**
     * 新增角色
     * @param {*}
     */
    addRoleClick() {
      this.title = "新增角色";
      this.addEditDialogVisible = true;
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row) {
      this.editId = row.id;
      this.title = "编辑角色";
      this.addEditDialogVisible = true;
      this.isCheck = true;
       this.$api.roleDetail(this.editId).then((response) => {
        this.$nextTick(() => {
          this.addEditForm.roleNameInput = response.data.result.name;
          this.addEditForm.roleCodeInput = response.data.result.code;
          var index = this.addEditForm.roleCodeInput.lastIndexOf("_");
          this.addEditForm.roleCodeInput =
            this.addEditForm.roleCodeInput.substring(
              index + 1,
              this.addEditForm.roleCodeInput.length
            );

          this.addEditForm.checkedIds = response.data.result.permissionIds;
          this.isCheck = false;
        });
      });
    },

    /**
     * 新增/编辑保存按钮
     * @param {*}
     */
    addEditSaveClick() {
      this.$refs.addEditFormRef.validate(async (boolean) => {
        if (boolean) {
          let treeActiveArr = this.$refs.treeRef
            .getCheckedKeys()
            .concat(this.$refs.treeRef.getHalfCheckedKeys());
          let data = {
            id: this.editId,
            code: this.addEditForm.roleCodeInput,
            name: this.addEditForm.roleNameInput,
            permissionIds: treeActiveArr,
          };
          if (this.title == "新增角色") {
             this.$api.addRole(data).then((response) => {
              console.log(response);
              if (response.data.code == "00000") {
                this.$message.success("新增成功");
                this.addEditDialogVisible = false;
                this.getRoleList();
              }
            });
          } else {
             this.$api.editRole(data).then((response) => {
              console.log(response);
              if (response.data.code == "00000") {
               this.$message.success("修改成功");
              this.addEditDialogVisible = false;
              this.getRoleList();
              }
            });
          }
        }
      });
    },

    /**
     * 新增对话框打开时回调
     * @param {*}
     */
    addEditDialogOpen() {
      if (this.$refs.addEditFormRef) {
        this.$refs.addEditFormRef.resetFields();
        this.$refs.treeRef.setCheckedKeys([]);
        for (let i = 0; i < this.data.length; i++) {
          this.$refs.treeRef.store.nodesMap[this.data[i].id].expanded = false;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.roleList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
   .topBtn {
    margin: 10px 0;
text-align: right;
  }
  .tableBox {
    flex: 1;
  }

  .addEditRoleDialog {
    .el-form-item {
      &.roleCode {
        .item {
          padding-top: 6px;
          box-sizing: border-box;
        }
      }
      .permissions {
        height: 500px;
        overflow: auto;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409EFF;
  background-color: #409EFF;
}
/deep/.el-form-item {
   margin-bottom: 12px;
}
</style>